<template>
  <div class="login">
    <!-- 导航栏 -->
    <nav-bar class="login-navbar">
      <div slot="left" class="arrow" @click="fhClick">
        <img src="~assets/img/login/arrow-left.svg" alt="" />
      </div>
      <div slot="center">
        <span>{{ message }}</span>
      </div>
    </nav-bar>

    <!-- 登录表单 -->
    <form action="">

      <label for="username">
        <input type="text" id='username' placeholder="请输入用户名" v-model='user.userName' />
      </label>

      <label for="psd">
        <input type="password" id='psd' placeholder="请输入密码" v-model='user.psw' />
      </label>
      
      <div class="mes">
        <a @click="toRegiserClick">没有账号，去注册</a>
      </div>

      <button type="button" @click='loginClick'>{{ message }}</button>
    </form>
  </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";

import {SIGNIN} from 'store/mutaions-types.js'

export default {
  name: "login",
  data() {
    return {
      message: "登录",
      user: {
        userName: '',
        psw: ''
      }
    };
  },
  components: {
    NavBar,
  },
  methods: {
    fhClick() {
      this.$router.push("/main/profile");
    },
    toRegiserClick() {
      this.$router.push("/register");
    },
    loginClick() {
      // 判断用户是否输入 用户名 密码
      if (!this.user.userName || !this.user.psw) {
        this.$toast.show('请输入用户名和密码再登录')
        return
      }
      
      // 发送登录请求
      const user = {}
      user.user = this.user.userName
      user.psw = this.user.psw

      this.$store.dispatch(SIGNIN, user)
        .then((res) => {
          // 根据返回的 res.code 判断是否登录成功  
          // 200 登录成功
          // 201 密码错误
          // 202 账号不存在

          if (res.code === 200) {
            this.$toast.show(res.message)
            // 跳转路由到首页
            this.$router.push('/main/profile')
          }else {
            this.$toast.show(res.message)
          }
        })
    }
  },
};
</script>

<style scoped>
.arrow {
  width: 100%;
  height: 100%;
}
.arrow img {
  width: 30px;
  margin-top: 8px;
}

.login-navbar {
  background-color: var(--color-tint);
  color: #fff;
}

form {
  text-align: center;
}

input,
button {
  width: 90%;
  height: 40px;
  margin-top: 20px;
  border-radius: 8px;
  border: 1px solid #ccc;
}
input {
  font-size: 12px;
  padding: 0px 5px;
}
button {
  background-color: var(--color-tint);
  color: #fff;
  font-weight: 700;
}

.mes {
  width: 100%;
  text-align: right;
  font-size: 12px;
  margin-top: 10px;
  text-decoration: underline;
  padding-right: calc(5%);
}
</style>